package com.yl.chainStore.services.impl.sick

import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.yl.chainStore.common.enums.Status
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.entity.company.SickCustomerAccessLogModel
import com.yl.chainStore.entity.company.SickCustomerAccessLogModelDetail
import com.yl.chainStore.entity.sick.SickCustomerAccessLog
import com.yl.chainStore.mapper.company.SickCustomerAccessLogModelDetailMapper
import com.yl.chainStore.mapper.company.SickCustomerAccessLogModelMapper
import com.yl.chainStore.mapper.sick.SickCustomerAccessLogMapper
import com.yl.chainStore.pojo.vo.company.SickCustomerAccessLogModelSelectVo
import com.yl.chainStore.services.sick.ISickCustomerAccessLogModelService
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import org.springframework.stereotype.Service
import java.util.*


@Service
class SickCustomerAccessLogModelServiceImpl(
    private val sickCustomerAccessLogModelMapper: SickCustomerAccessLogModelMapper,
    private val sickCustomerAccessLogModelDetailMapper: SickCustomerAccessLogModelDetailMapper,

    private val sickCustomerAccessLogMapper: SickCustomerAccessLogMapper
) : ISickCustomerAccessLogModelService {

    override fun getModelInfo(id: Long): SickCustomerAccessLogModel? {
        return sickCustomerAccessLogModelMapper.selectById(id)
    }

    override fun setDetails(model: SickCustomerAccessLogModel) {
        model.details = sickCustomerAccessLogModelDetailMapper.selectList(
            Wrappers.query<SickCustomerAccessLogModelDetail?>()
                .eq("model_id", model.id)
                .orderByAsc("order_num")
        )
    }

    override fun updateModel(model: SickCustomerAccessLogModel): ResponseBody {
        if (model.details == null || model.details!!.size == 0) {
            return returnError(ErrorCode.DATA_SAVE_FAILED, "请添加随访模版内容")
        }
        val oldModel = sickCustomerAccessLogModelMapper.selectById(model.id) ?: return returnError(
            ErrorCode.DATA_IS_NOT_FIND,
            "未找到模版，请刷新重试"
        )
        oldModel.name = model.name
        oldModel.createType = model.createType
        oldModel.orderNum = model.orderNum
        oldModel.updateTime = Date()
        oldModel.updateUserId = getContext().userId
        sickCustomerAccessLogModelMapper.updateById(oldModel)
        sickCustomerAccessLogModelDetailMapper.delete(
            Wrappers.query<SickCustomerAccessLogModelDetail?>().eq("model_id", model.id)
        )
        var orderNum = 1
        for (detail in model.details!!) {
            if (detail.timeNumber < 0) {
                return returnError(ErrorCode.DATA_SAVE_FAILED, "间隔时间不能小于0")
            }
            detail.id = 0L
            detail.orderNum = orderNum
            detail.modelId = model.id
            sickCustomerAccessLogModelDetailMapper.insert(detail)
        }
        return returnSuccess()
    }

    override fun updateStatus(id: Long, status: Status): ResponseBody {

        val model = sickCustomerAccessLogModelMapper.selectById(id) ?: return returnError(
            ErrorCode.DATA_IS_NOT_FIND,
            "未找到模版，请刷新重试"
        )
        model.status = status
        sickCustomerAccessLogModelMapper.updateById(model)
        return returnSuccess()
    }

    override fun getNextDetail(detailId: Long): SickCustomerAccessLogModelDetail? {
        val detail = sickCustomerAccessLogModelDetailMapper.selectById(detailId) ?: return null
        val orderNum = detail.orderNum + 1
        val details = sickCustomerAccessLogModelDetailMapper.selectList(
            Wrappers.query<SickCustomerAccessLogModelDetail?>()
                .eq("model_id", detail.modelId)
                .eq("order_num", orderNum)
        )
        if (details == null || details.size == 0) {
            return null
        }
        return details[0]
    }




    override fun move(modelId: Long, moveType: TypeEnum, vo: SickCustomerAccessLogModelSelectVo): ResponseBody {
        return if (moveType == TypeEnum.MOVE_TYPE_UP) {
            moveUp(modelId, vo)
        } else {
            moveDown(modelId, vo)
        }

    }

    override fun moveByIds(ids: List<Long>): ResponseBody {
        val oldModels = sickCustomerAccessLogModelMapper.selectList(
            Wrappers.query<SickCustomerAccessLogModel?>()
                .`in`("id", ids)
                .orderByAsc("order_num")
        )

        for ((index, id) in ids.withIndex()) {
            val oldModel = oldModels[index]
            if (id != oldModel.id) {
                //排序不一样，需要替换
                sickCustomerAccessLogModelMapper.update(
                    null,
                    Wrappers.update<SickCustomerAccessLogModel?>().eq("id", id).set("order_num", oldModel.orderNum)
                )
            }
        }


        return returnSuccess()
    }


    private fun moveUp(modelId: Long, vo: SickCustomerAccessLogModelSelectVo): ResponseBody {
        val model = sickCustomerAccessLogModelMapper.selectById(modelId)
        val wrapper = Wrappers.query<SickCustomerAccessLogModel?>()
        if (vo.status != null) {
            wrapper.eq("status", vo.status!!.code)
        }
        wrapper.eq("sub_company_id", model.subCompanyId)
            .eq("enabled", 1).lt("order_num", model.orderNum)
            .orderByDesc("order_num")
            .last("limit 1")
        val onList = sickCustomerAccessLogModelMapper.selectList(wrapper)
        if (onList == null || onList.size == 0) {
            return returnError(ErrorCode.OPERATION_DATA_ERROR, "已经是最顶部")
        }
        val onModel = onList[0]
        exchangePlace(model, onModel)
        return returnSuccess()
    }

    private fun moveDown(modelId: Long, vo: SickCustomerAccessLogModelSelectVo): ResponseBody {
        val model = sickCustomerAccessLogModelMapper.selectById(modelId)
        val wrapper = Wrappers.query<SickCustomerAccessLogModel?>()
        if (vo.status != null) {
            wrapper.eq("status", vo.status!!.code)
        }
        wrapper.eq("sub_company_id", model.subCompanyId)
            .eq("enabled", 1).gt("order_num", model.orderNum)
            .orderByAsc("order_num")
            .last("limit 1")
        val downList = sickCustomerAccessLogModelMapper.selectList(wrapper)
        if (downList == null || downList.size == 0) {
            return returnError(ErrorCode.OPERATION_DATA_ERROR, "已经是最底部")
        }
        val downModel = downList[0]
        exchangePlace(model, downModel)
        return returnSuccess()

    }

    /**
     * 交换2个模版显示位置
     */
    private fun exchangePlace(model: SickCustomerAccessLogModel, secModel: SickCustomerAccessLogModel) {
        val orderNum = model.orderNum
        model.orderNum = secModel.orderNum
        secModel.orderNum = orderNum
        sickCustomerAccessLogModelMapper.updateById(model)
        sickCustomerAccessLogModelMapper.updateById(secModel)
    }
}
